package com.seal.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.seal.comm.utils.Page;
import com.seal.dao.BaseDaoImpl;
import com.seal.dao.IRegUserinfoDao;
import com.seal.dto.RegUserinfoDto;
import com.seal.model.RegUserinfo;

@Repository("regUserinfoDaoImpl")
public class RegUseinfoDaoImpl extends BaseDaoImpl implements IRegUserinfoDao{

	public void addRegUserinfo(RegUserinfo ca) throws Exception {
		this.save(ca);
	}

	public void updateRegUserinfo(RegUserinfo ca) throws Exception {
		this.update(ca);
	}
	
	public RegUserinfo getRegUserinfoByUserId(String userId) throws Exception {
		String hql = "from RegUserinfo t where t.userId = ?";
		return (RegUserinfo) this.getSessionFactory()
				.getCurrentSession().createQuery(hql).setString(0, userId)
				.uniqueResult();
	}
	
	public List<RegUserinfo> getAllRegUserinfo(RegUserinfoDto dto, Page page)throws Exception {
		StringBuffer hql=new StringBuffer("from RegUserinfo t where 1=1");

		Query query = this.getSession().createQuery(hql.toString());
		query.setProperties(dto);
		if (null != page) {
			query.setFirstResult(page.getFirstResult());
			query.setMaxResults(page.getPageSize());
			String countSql="select count(t) "+hql.toString();

			Query queryCount = this.getSession().createQuery(countSql);
			queryCount.setProperties(dto);
			page.setTotalNumber(Integer.parseInt(queryCount.uniqueResult().toString()));
		}
		
		return query.list();
	}
	
	
	public boolean checkEmailExists(String userId, String email) throws Exception {
		String hql = "from RegUserinfo t where 1=1 ";
		if(userId !=null && !"".equals(userId.trim())){
			hql +=" and t.userId ='"+userId+"'";
		}
		
		if(email !=null && !"".equals(email.trim())){
			hql +=" and t.email ='"+email+"'";
		}
		
		Query query = this.getSessionFactory().getCurrentSession().createQuery(hql);
		List list=query.list();
		if (list != null && list.size() > 0)
			return true;
		else
			return false;
	}

	public RegUserinfo getRegUserinfoByEmail(String email) throws Exception {
		String hql = "from RegUserinfo t where t.email = ?";
		return (RegUserinfo) this.getSessionFactory()
				.getCurrentSession().createQuery(hql).setString(0, email)
				.uniqueResult();
	}
	
}
